<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>药品商城</title>
</head>
<body>
<h1>药品列表</h1>
<table border="1" id="medicineTable">
    <thead>
    <tr>
        <th>ID</th>
        <th>药品名称</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody></tbody>
</table>
<form id="editMedicineForm" style="display: none;">
    <label for="medicineNameEdit">药品名称:</label>
    <input type="text" id="medicineNameEdit" name="medicineName">
    <label for="medicineEfficacyEdit">药品功效:</label>
    <textarea id="medicineEfficacyEdit" name="medicineEfficacy"></textarea>

    <label for="medicinePriceEdit">药品价格:</label>
    <input type="number" id="medicinePriceEdit" name="medicinePrice" step="0.01">

    <label for="medicineNumEdit">药品库存:</label>
    <input type="number" id="medicineNumEdit" name="medicineNum">

    <button type="submit">保存修改</button>
    <button type="button" id="cancelEditBtn">取消</button>
</form>
<div id="medicineDetailTemplate" style="display:none;">
    <form id="medicineDetailForm">
        <label for="medicineName">药品名称:</label>
        <input type="text" id="medicineName" disabled><br>
        <label for="medicineEfficacy">药品药效:</label>
        <textarea id="medicineEfficacy" disabled></textarea><br>
        <label for="medicinePrice">药品价格:</label>
        <input type="number" id="medicinePrice" disabled><br>
        <label for="medicineNum">药品库存:</label>
        <input type="number" id="medicineNum" disabled><br>
    </form>
</div>
<form id="addMedicineForm" class="medicine-form">
    <h1>药品添加</h1>
    <div class="form-group">
        <label for="medicineName">药品名称：</label>
        <input type="text" id="medicineNameF" name="medicineNameF" required class="form-control">
    </div>
    <div class="form-group">
        <label for="medicineEfficacy">药品功效：</label>
        <textarea id="medicineEfficacyF" name="medicineEfficacyF" required class="form-control"></textarea>
    </div>
    <div class="form-group">
        <label for="medicinePrice">药品价格：</label>
        <input type="number" id="medicinePriceF" name="medicinePriceF" step="0.01" required class="form-control">
    </div>
    <div class="form-group">
        <label for="medicineNum">药品库存数量：</label>
        <input type="number" id="medicineNumF" name="medicineNumF" required class="form-control">
    </div>
    <button type="submit" class="btn btn-primary">添加药品</button>
</form>
<div id="cart-summary">
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
    function getAllMedicines() {
        $.get("http://localhost:8080/Medicine/findAllMedicine", function(response) {
            if (response.code === "200") {
                var medicines = response.data;
                var tbody = $("#medicineTable tbody");
                tbody.empty();
                for (var i = 0; i < medicines.length; i++) {
                    var medicine = medicines[i];
                    var tr = $("<tr></tr>");
                    tr.append("<td>" + medicine.id + "</td>");
                    tr.append("<td>" + medicine.name + "</td>");
                    tr.append('<td><a href="#" class="viewDetailBtn" data-id="' + medicine.id + '">查看详情</a> | <button class="deleteBtn" data-id="' + medicine.id + '">删除</button> | <button class="edit-medicine-btn" data-id="' + medicine.id + '">修改</button> |<button class="add-to-cart-btn" data-id=' + medicine.id + '>加入购物车</button> </td>');
                    tbody.append(tr);
                }
            } else {
                alert("获取药品信息失败：" + response.msg);
            }
        });
    }
    getAllMedicines();
    $(document).on("click", ".deleteBtn", function() {
        var id = $(this).data("id");
        if (confirm("确定要删除该药品吗？")) {
            $.ajax({
                url: "http://localhost:8080/Medicine/deleteMedicine/" + id,
                type: "DELETE",
                success: function(response) {
                    if (response.code === "200") {
                        alert("删除成功");
                        getAllMedicines();
                    } else {
                        alert("删除失败：" + response.msg);
                    }
                }
            });
        }
    });
    $(document).ready(function() {
        $("#addMedicineForm").on("submit", function(event) {
            event.preventDefault();
            var medicineName = $("#medicineNameF").val();
            var medicineEfficacy = $("#medicineEfficacyF").val();
            var medicinePrice = $("#medicinePriceF").val();
            var medicineNum = $("#medicineNumF").val();
            console.log("medicineName:", $("#medicineNameF").val());
            console.log("medicineEfficacy:", $("#medicineEfficacyF").val());
            console.log("medicinePrice:", $("#medicinePriceF").val());
            console.log("medicineNum:", $("#medicineNumF").val());
            var data = {
                name: medicineName,
                efficacy: medicineEfficacy,
                price: medicinePrice,
                num: medicineNum
            };
            console.log(data);
            $.ajax({
                url: "http://localhost:8080/Medicine/addMedicine",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(data),
                success: function(response) {
                    if (response.code === "200") {
                        alert("添加成功");
                        getAllMedicines();
                    } else {
                        alert("添加失败：" + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    alert("请求失败: " + error);
                }
            });
        });
    });
    function showMedicineDetailDialog(medicine) {
        var $template = $("#medicineDetailTemplate").clone();
        $template.find("#medicineName").val(medicine.name);
        $template.find("#medicineEfficacy").val(medicine.efficacy);
        $template.find("#medicinePrice").val(medicine.price);
        $template.find("#medicineNum").val(medicine.num);
        $template.dialog({
            title: "药品详情",
            modal: true,
            width: 400,
            buttons: {
                "关闭": function() {
                    $(this).dialog("close");
                }
            }
        });
    }
    $(document).on("click", ".viewDetailBtn", function() {
        var id = $(this).data("id");
        $.get("http://localhost:8080/Medicine/findMedicineById/" + id, function(response) {
            if (response.code === "200") {
                var medicine = response.data;
                showMedicineDetailDialog(medicine); // 显示药品详情对话框
            } else {
                alert("获取药品详情失败：" + response.msg);
            }
        });
    });
    $(document).on('click', '.edit-medicine-btn', function () {
        var id = $(this).data("id");
        $.ajax({
            url: 'http://localhost:8080/Medicine/findMedicineById/' + id,
            type: 'GET',
            dataType: 'json',
            success: function (response) {
                $('#medicineNameEdit').val(response.data.name);
                $('#medicineEfficacyEdit').val(response.data.efficacy);
                $('#medicinePriceEdit').val(response.data.price);
                $('#medicineNumEdit').val(response.data.num);
                $('#editMedicineForm').show();
            },
            error: function (xhr, status, error) {
                console.error("AJAX Error: " + status + "\nError: " + error);
            }
        });
        $('#cancelEditBtn').click(function () {
            $('#editMedicineForm').hide();
            $('#editMedicineForm')[0].reset();
        });
        $('#editMedicineForm').on('submit', function (event) {
            event.preventDefault();
            // 收集修改后的数据
            var medicineNameEdit = $(this).find('#medicineNameEdit').val();
            var medicineEfficacyEdit = $(this).find('#medicineEfficacyEdit').val();
            var medicinePriceEdit = $(this).find('#medicinePriceEdit').val();
            var medicineNumEdit = $(this).find('#medicineNumEdit').val();
            var data = {
                id:id,
                name: medicineNameEdit,
                efficacy: medicineEfficacyEdit,
                price: medicinePriceEdit,
                num: medicineNumEdit
            };
            console.log(data);
            $.ajax({
                url: "http://localhost:8080/Medicine/updateMedicine",
                type: "Put",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(data),
                success: function (response) {
                    if (response.code === "200") {
                        alert("修改成功");
                        getAllMedicines();
                    } else {
                        alert("修改失败：" + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    alert("请求失败: " + error);
                }
            });
            $(this).trigger('reset'); // 清空表单字段
            $(this).hide(); // 隐藏修改表单
            });
    });
    $(document).on('click', '.add-to-cart-btn', function () {
        var medicineId = $(this).data("id");
        var medicineName;
        var medicinePrice;
        var medicineNum;
        console.log(medicineId);
        $.ajax({
            url: 'http://localhost:8080/Medicine/findMedicineById/' + medicineId,
            type: 'GET',
            dataType: 'json',
            success: function (response) {
                console.log(response);
                if (response.data) {
                    medicineName = response.data.name;
                    medicinePrice = response.data.price;
                    medicineNum = prompt("请输入购买数量：");
                    if (medicineNum && !isNaN(medicineNum)) {
                        // 第二个AJAX请求：将药品加入购物车
                        $.ajax({
                            url: 'http://localhost:8080/Medicine/addToShopping',
                            type: 'POST',
                            contentType: "application/json; charset=utf-8",
                            data: JSON.stringify({ // 将JavaScript对象转换为JSON字符串
                                medicineId: medicineId,
                                medicineName: medicineName,
                                medicineNum: medicineNum,
                                medicinePrice: medicinePrice,
                                totalPrice: medicinePrice * medicineNum
                            }),
                            success: function (response) {
                                if (response.code === "200") {
                                    // 更新购物车显示
                                    updateCartDisplay(response.data);
                                    fetchCartData();
                                    alert("已成功加入购物车");
                                } else {
                                    alert("加入购物车失败：" + response.msg);
                                }
                            },
                            error: function (xhr, status, error) {
                                alert("请求失败: " + error);
                            }
                        });
                    } else {
                        alert("请输入有效的购买数量");
                    }
                } else {
                    alert("未找到药品信息");
                }
            },
            error: function (xhr, status, error) {
                console.error("AJAX Error (查找药品): " + status + "\nError: " + error);
            }
        });
    });
    function fetchCartData() {
        $.ajax({
            url: 'http://localhost:8080/Medicine/findAllShoppingList',
            type: 'GET',
            dataType: 'json',
            success: function(cartData) {
                console.log("aaa"+cartData)
                updateCartDisplay(cartData);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error fetching cart data:', textStatus, errorThrown);
            }
        });
    }
    function updateCartDisplay(cartData) {
        var totalPrice = 0;
        $.each(cartData.data, function(index, item) {
            if (item === null || typeof item !== 'object') {
                console.error('Invalid item in cartData:', item);
                return;
            }
            var medicineItemHtml = `
            <div class="cart-item">
                <span class="medicine-name">药品名称：${item.medicineName}</span>
                <span class="medicine-num">购买数量：${item.medicineNum}</span>
                <span class="medicine-price">药品单价：${item.medicinePrice}</span>
            </div>
        `;
            $('#cart-summary').append(medicineItemHtml);
            if (item.medicineNum !== null && item.medicinePrice !== null) {
                totalPrice += item.medicinePrice * item.medicineNum;
            } else {
                console.error('Invalid data in item:', item);
            }
        });
        $('#cart-summary').append(`<div class="total-price">总价: ${totalPrice}</div>`);
    }
    fetchCartData();
</script>
</body>
</html>
<style>
    .medicine-form {
        max-width: 400px;
        margin: 0 auto;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 5px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    .form-group {
        margin-bottom: 15px;
    }

    .form-group label {
        display: block;
        margin-bottom: 5px;
    }

    .form-control {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-sizing: border-box;
    }

    .btn {
        display: inline-block;
        padding: 10px 20px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    .btn:hover {
        background-color: #0056b3;
    }
</style>
